<template>
  <a-card>
    <a-spin :spinning="spinning" size="large">
      <Header :title="'返回'" subTitle="券延长" :hasBackPath="true" @headerBack="$router.back()"></Header>
      <a-form-model
        ref="rulesForm"
        :model="form"
        :rules="rules"
        :labelCol="{ lg: { span: 4 }, sm: { span: 5 } }"
        :wrapperCol="{ lg: { span: 14 }, sm: { span: 17 } }"
      >
        <a-form-model-item   label="延期原因" prop="remark">
          <a-textarea
            allowClear
            :maxLength="50"
            v-model="form.remark"
            placeholder="请说明原因"
          />
        </a-form-model-item>
        <a-form-model-item  label="延期对象" prop="delayType">
          <a-radio-group v-model="form.delayType" @change="delayTypeChange">
            <a-radio :value="1">优惠券号</a-radio>
            <a-radio :value="2">券规则</a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="添加需要延期的优惠券号" class="hidden-title">
          <a-input
            style="width: 40%"
            allowClear
            v-model="no"
            :placeholder="form.delayType == 1 ? '请填写优惠券号' : '请填写AWARDID'"
          />
          <a-button type="primary" style="margin-left: 15px;" @click="handleAddCoupon">确认添加</a-button>
<!--          :file-list="fileList" :remove="handleRemove" :before-upload="beforeUpload"-->
          <a-upload
            accept=".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            name="file"
            :showUploadList="false"
            :multiple="false"
            :data="{
              type: form.delayType
            }"
            :action="uploadUrl"
            @change="handleChange"
          >
            <a-button style="margin-left: 15px;">批量添加</a-button>
          </a-upload>
          <div>当前共成功添加了{{data.length}}个券号，请确保填写信息正确！<span style="text-decoration: underline;color: blue;cursor: pointer" @click="handleExport">点击下载导入模版</span></div>
          <a-table bordered :pagination="pagination"  :columns="form.delayType == 1 ? noColumns : ruleColumns" :data-source="data" :rowKey="(record, index) => index" @change="tableChange" size="middle">
            <span slot="action" slot-scope="text, record">
              <a-popconfirm title="请确认是否删除本条信息？" @confirm="handleDeletCoupon(record.voucherNo)">
                <a-icon type="delete" style="cursor: pointer;" />
              </a-popconfirm>
            </span>
          </a-table>
        </a-form-model-item>
        <a-form-model-item label="延期类型" prop="optType" >
          <a-radio-group v-model="form.optType">
            <a-radio :value="1" style="margin: 10px 0;">指定日期
              <br>
                <a-date-picker
                  v-if="form.optType == 1"
                  v-model="form.delayDate"
                  type="date"
                  valueFormat="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                  placeholder="请选择"
                />
            </a-radio>
            <br>
            <a-radio :value="2">原到期时间顺延 <a-input-number
              style="width: 100px;"
              allowClear
              :min="1"
              :max="1000"
              :precision="0"
              v-model="form.delayDays"
              placeholder=""
            /> 天</a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-divider />
        <a-form-model-item :wrapperCol="{ span: 24 }" style="text-align: center">
          <a-button type="primary" @click="handleSubmit">确定</a-button>
          <div style="color: red;">一旦确认延期，无法撤回，请仔细检查需延期优惠券号！</div>
        </a-form-model-item>
      </a-form-model>
    </a-spin>
  </a-card>
</template>
<script>
import Header from '@/views/box/components/layouts/Header'
import { mapGetters } from 'vuex'
import { sendList, forDelay, validityDelay } from '@/api/marketingCenter/boCouponExtension'
  const noColumns = [
    {
      title: '序号',
      width: 1,
      align: 'center',
      customRender: (text,record,index) => `${index+1}`
    },
    {
      title: '优惠券号',
      width: 4,
      align: 'center',
      dataIndex: 'voucherNo'
    },
    {
      title: '券名称',
      width: 4,
      align: 'center',
      dataIndex: 'voucherName'
    },
    {
      title: '面额',
      width: 4,
      align: 'center',
      dataIndex: 'voucherAmt'
    },
    {
      title: '折扣',
      width: 4,
      align: 'center',
      dataIndex: 'voucherDiscount'
    },
    {
      title: '有效期至',
      width: 4,
      align: 'center',
      dataIndex: 'validDate'
    },
    {
      title: '操作',
      width: 1,
      align: 'center',
      scopedSlots: { customRender: 'action' }
    }
  ];
  const ruleColumns = [
    {
      title: '序号',
      width: 1,
      align: 'center',
      customRender: (text,record,index) => `${index+1}`
    },
    {
      title: 'AWARDID',
      width: 4,
      align: 'center',
      dataIndex: 'awardId'
    },
    {
      title: '券名称',
      width: 4,
      align: 'center',
      dataIndex: 'voucherName'
    },
    {
      title: '面额',
      width: 4,
      align: 'center',
      dataIndex: 'voucherAmt'
    },
    {
      title: '折扣',
      width: 4,
      align: 'center',
      dataIndex: 'voucherDiscount'
    },
    {
      title: '操作',
      width: 1,
      align: 'center',
      scopedSlots: { customRender: 'action' }
    }
  ];

  export default {
    components: {
      Header
    },
    data() {
      return {
        no: '',
        uploadUrl: forDelay,
        pagination: {
          current: 1,
          pageSize: 10,
          total: 0,
          showTotal: total => `共有 ${total} 条数据`
        },
        data:[],
        noColumns,
        ruleColumns,
        spinning: false,
        form: {
          optType: 1,
          delayType: 1,
          delayDate: '',
          remark: '',
          delayDays: ''
        },
        rules: {
          optType: [
            { required: true, message: '请选择', trigger: 'change'}
          ],
          delayType: [
            { required: true, message: '请选择', trigger: 'change'}
          ],
          remark: [
            { required: true, message: '请填写', trigger: 'blur' }
          ]
        }
      }
    },
    computed: {
    },
    watch: {
    },
    activated() {
    },
    created() {
    },
    mounted() {
    },
    methods: {
      ...mapGetters(['nickname', 'avatar', 'userInfo']),
      delayTypeChange() {
        this.pagination.current = 1
        this.data = []
      },

      handleAddCoupon() {
        console.log(this.no, this.data, 'this.data')
        const msg = this.form.delayType == 1 ? '请填写优惠券号' : '请填写AWARDID'
        const len = this.data.filter(e => e.voucherNo == this.no || e.awardId == this.no)
        if (!this.no) {
          this.$message.info(msg)
          return false
        }
        if (len.length > 0) {
          this.$message.info('该券号已存在')
          return false
        }
        const data = {
          voucherNo: this.form.delayType == 1 ? this.no : null,
          awardId: this.form.delayType == 2 ? this.no : null
        }
        sendList(data).then(res => {
          if (res.code == 200) {
            console.log(res.data, 'res.data')
            this.data.push(res.data)
          } else {
            this.$message.warning(res.msg || res.message)
          }
        })
      },

      tableChange(pagination) {
        const pager = { ...this.pagination }
        pager.current = pagination.current
        this.pagination = pager
      },

      // 删除
      handleDeletCoupon(voucherNo) {
        const index = this.data.findIndex(e => e.voucherNo === voucherNo)
        this.data.splice(index, 1)
      },

      // 批量添加发放对象
      handleChange(info) {
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList)
        }
        if (info.file.status === 'done') {
          const {msg, message, code, data} = info.file.response
          if (code == 200 ) {
            this.data = data.excelData
            if(data.errorExcelLink != ''){
              this.$confirm({
              title: `部分数据有误，无法导入`,
              content: '下载错误数据，查看错误原因',
              closable: false,
              okText: '下载',
              cancelText: '取消',
              onOk() {
                window.location.href = data.errorExcelLink
              },
              onCancel() {}
            })
            }
          } else {
            this.$message.error(msg | message)
          }
        } else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} file upload failed.`)
        }
      },


      //下载导入模板
      handleExport() {
        const downUrl = this.form.delayType == 2 ? 'https://picttype1.jnby.com/%E5%88%B8%E5%BB%B6%E9%95%BF%E5%88%B8%E8%A7%84%E5%88%99%E5%AF%BC%E5%85%A5%E6%A8%A1%E7%89%88.xlsx' : 'https://picttype1.jnby.com/%E5%88%B8%E5%BB%B6%E9%95%BF%E4%BC%98%E6%83%A0%E5%88%B8%E5%AF%BC%E5%85%A5%E6%A8%A1%E7%89%88.xlsx'
        window.location.href = downUrl
      },


      handleSubmit() {
        this.$refs.rulesForm.validate(valid => {
          if (valid) {
            const {optType, delayDate, delayDays, delayType} = this.form
            if (!this.data.length) {
              this.$message.info('请添加延期对象！')
              return
            }
            if (optType == 1 && !delayDate) {
              this.$message.info('请选择指定日期！')
              return
            }
            if (optType == 2 && !delayDays) {
              this.$message.info('请填写原到期时间顺延天数！')
              return
            }
            const data = {
              voucherNos: delayType == 1 ? this.data.map(e => e.voucherNo) : null,
              awardIds: delayType == 2 ? this.data.map(e => e.awardId) : null,
              ...this.form,
              delayDate: optType == 1 ? delayDate : null,
              delayDays: optType == 2 ? delayDays : null,
              workNo: this.userInfo().workNo
            }
            this.spinning = true
            validityDelay(data).then(res => {
              this.spinning = false
              if (res.code === 200) {
                this.$router.go(-1)
              } else {
                this.$message.warning(res.msg || res.message)
              }
            }).catch(err => {
              this.spinning = false
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        })
      }
    }
  }
</script>
<style scoped>
  .association-list /deep/td{
    padding-bottom: 0 !important;
  }
  .hidden-title  /deep/.ant-form-item-label > label{
    visibility: hidden;
  }
  .show-title  /deep/.ant-form-item-label > label{
    visibility: visible;
    width: 20%;
  }
</style>
